/***
 * Andmin - Joomla administrator access from Android phone
 * @license http://www.gnu.org/licenses/gpl-3.0.txt
 * @author codegravity.com
 * @copyright (C) 2011 by Matej Koval - All rights reserved!
 * @website http://www.codegravity.com
 */

package com.codegravity.mobile.andmin;

import org.xmlpull.v1.XmlPullParser;
import com.codegravity.mobile.andmin.R;
import android.app.Activity;
import android.content.Intent;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.provider.Browser;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.HttpAuthHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

/*
 * Main Activity to display web browser
 */
public class Andmin extends Activity {
    /** Called when the activity is first created. */
	WebView web;
	final Activity activity = this;
	private boolean isLogin = false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set layout to display
        setContentView(R.layout.main);
        // load setting from configuration
        AndminSetting.Load(this);    
        // if this is the frist run, will display setting activity for user setting param for app
        if (AndminSetting.isFirstRun()) {
        	startActivityForResult(new Intent(Andmin.this, AndminSettingActivity.class), 1);
        } else {
        	init();
        }        
        
    }
    /***
     * try when user finish setting
     */
    @Override
	protected void onActivityResult(int requestCode, int resultCode,
            Intent data) {
        if (requestCode == 1) {
        	if (!AndminSettingActivity.isSaveData) {
        		if (AndminSetting.isFirstRun()) {
        			this.finish();
        		}
        	} else {
        		init();
        	}
        }
    }
    /***
     * Display menu foo the app
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	return true;
    }
    /***
     * Event when user clicks menu of the app.
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {    	
    	// Handle item selection
    	switch (item.getItemId()) {
    		case R.id.itemRefresh:
    			// refresh the web browser control
    			web.reload();    			
    			break;
    		case R.id.itemSetting:
    			// start Setting Activity so that user can setting some params.
    			startActivityForResult(new Intent(Andmin.this, AndminSettingActivity.class), 1);
    			break;    		
    	}    	
    	return super.onOptionsItemSelected(item);
    }
    /***
     * init web browses to connect to website and display content of website
     */
	private void init() {    
		//
		isLogin = false;
		final String component = AndminSetting.getJoomplaComponent();
		web = (WebView) findViewById(R.id.webkitWebView1);
		final String urlIntristion = getInstructionsUrl();
		// set Http Auth User and Http Auth Password
		if (!"".equals(AndminSetting.getHttpAuthUsername())) {
			web.setHttpAuthUsernamePassword(AndminSetting.getWebUrl(), "", AndminSetting.getHttpAuthUsername(), AndminSetting.getHttpAuthPassword());
		}
		// set setting for web browser.
    	web.getSettings().setJavaScriptEnabled(true);
    	web.getSettings().setSavePassword(false);
    	web.clearHistory();
    	web.clearCache(true);
    	web.clearFormData();
//    	FrameLayout mContentView = (FrameLayout)getWindow().getDecorView().findViewById(android.R.id.content);;
//    	final View zoom = this.web.getZoomControls();
//        mContentView.addView(zoom, ZOOM_PARAMS);
//        zoom.setVisibility(View.GONE);
    	web.getSettings().setBuiltInZoomControls(true);
    	//if the app is gettting data from website, it will display "modmin loading....
    	web.setWebChromeClient(new WebChromeClient() {
             public void onProgressChanged(WebView view, int progress)
             {
            	 activity.setTitle("Andmin loading...");
            	 activity.setProgress(progress * 100);
                 if(progress == 100)
                	 activity.setTitle(R.string.app_name);
             }
         });    	
    	/* WebViewClient must be set BEFORE calling loadUrl! */  
    	web.setWebViewClient(new WebViewClient() {
    		@Override 
    		public void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm) {
    			// setting http auth username and http auth password if it recieved Http Auth Request.
    			handler.proceed(AndminSetting.getHttpAuthUsername(), AndminSetting.getHttpAuthPassword());
    		}
    	    @Override  
    	    public void onPageFinished(WebView view, String url)  
    	    { 
    	    	// Joomla 1.5: modlgn_username and modlgn_passwd
    	    	// Joomla 1.6: mod-login-username and mod-login-passwd
    	    	String username = AndminSetting.getUsername();
    	    	String password = AndminSetting.getPassword();
    	    	if (url.contains("option=" + component)) {
	    	    	String script = "javascript:if (document.getElementById('form-login') != null) {" +
											"if (window.document.getElementById('modlgn_username') != null) {" +
												"document.getElementById('modlgn_username').value ='" + username + "';" +
												"document.getElementById('modlgn_passwd').value ='" + password + "';" +		
											"} else {" +
												"document.getElementById('mod-login-username').value ='" + username + "';" +
												"document.getElementById('mod-login-password').value ='" + password + "';" +	
											"}" +
											"document.getElementById('form-login').submit();" +
									"} else {" +
										"if (document.getElementById('content-box').innerHTML.indexOf('Component not found') >= 0) {" +
											"window.location = '" +  urlIntristion + "'" + 
										"}" +
									"};";	    	    	
	    	    	web.loadUrl(script);
    	    	} else {
//    	    		web.loadUrl("http://www.joomlawatchdemo.com/administrator/index.php?option=com_joomlawatch");'
    	    		if (isLogin) {
    	    			AlertMessage.show("Login unsuccessful !", Andmin.this);
    	    			
    	    		} else {
	    	    		if (!url.equals(urlIntristion)) {
	    	    			web.loadUrl(AndminSetting.getFullWebUrl());
	    	    		}
    	    		}
    	    		isLogin = true;
    	    	}
    	    }
    	});    	
    	// load website from param that User set in Setting Activity
    	web.loadUrl(AndminSetting.getFullWebUrl());
    }
	/***
	 * function that reads file setting.xml and return the url for dispaly instruction information.
	 * @return Url for display instruction.
	 */
	private String getInstructionsUrl() {
		String url = "";
		XmlResourceParser parse = getResources().getXml(R.xml.setting);
		try {
			parse.next();
			int eventType = parse.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {
				if(eventType == XmlPullParser.TEXT) {
					url = parse.getText();
					return url;
			    }
				eventType = parse.next();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			
		}
		return url;
	}
}